package com.open.capacity.user.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.service.SysCompanyService;
import com.open.capacity.user.vo.SysCompanyExcel;
import com.open.capacity.user.vo.SysCompanyVo;
import com.open.capacity.utils.CollectionUtil;
import com.open.capacity.utils.encrypt.Md5Utils;
import com.open.capacity.vo.MapVo;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.list.TreeList;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 公司管理
 */
@RestController
@Api(tags = "公司模块api")
public class SysCompanyController {

    private static Logger logger = LoggerFactory.getLogger(SysCompanyController.class);

    @Autowired
    private SysCompanyService companyService;


    /**
     * 查询公司
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('company:get/companys')")
    @ApiOperation(value = "查询公司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父级id", required = false, dataType = "String")
    })
    @GetMapping("/companys")
    public Result<List<SysCompany>> findCompanys(@RequestParam Map<String, Object> params) {
        List<SysCompany> list = companyService.findCompanys(params);
        return Result.succeed(list);

    }

    /**
     * 查询公司tree
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('company:get/companys')")
    @ApiOperation(value = "查询公司tree")
    @GetMapping("/companys/tree")
    public Result<List<TreeVo>> treeCompanys(@RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        List<SysCompany> companys = companyService.findCompanys(params);
        List<TreeVo> treeList = new TreeList();
        companys.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getFullName());
            node.setTitle(m.getFullName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            if (m.getParentId().equals("0")) {
                node.setIsexpand(true);
            } else {
                node.setIsexpand(false);
            }
            node.setComplete(false);
            node.setParentId(m.getParentId());
            treeList.add(node);
        });

        //单个下级单位处理
        if (CollectionUtils.isNotEmpty(treeList) && treeList.size() == 1) {
            treeList.get(0).setParentId("0");
        }
        return Result.succeed(TreeVo.RecursiveBuilder(treeList, parentId));
    }


    /**
     * 查询公司tree -- 包含所有机构
     *
     * @param parentId
     * @return
     */
    @PreAuthorize("hasAuthority('company:get/companys')")
    @ApiOperation(value = "查询公司tree")
    @GetMapping("/companys/tree_all")
    public Result<List<TreeVo>> treeAllCompanys(@RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        List<SysCompany> companys = new ArrayList<>();
        SysCompany all = new SysCompany();
        all.setId("-1");
        all.setCode("-1");
        all.setParentId("0");
        all.setFullName("所有单位");
        companys.add(all);
        companys.addAll(companyService.findCompanys(params));
        List<TreeVo> treeList = new TreeList();
        companys.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getFullName());
            node.setTitle(m.getFullName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            if (m.getParentId().equals("0")) {
                node.setIsexpand(true);
            } else {
                node.setIsexpand(false);
            }
            node.setComplete(false);
            node.setParentId(m.getParentId());
            treeList.add(node);
        });

        return Result.succeed(TreeVo.RecursiveBuilder(treeList, parentId));
    }


    /**
     * 查询公司map
     *
     * @param ver
     * @return
     */
    @PreAuthorize("hasAuthority('company:get/companys')")
    @ApiOperation(value = "查询公司map")
    @GetMapping("/companys/map")
    public Result<MapVo> mapCompanys(@RequestParam(value = "ver", required = false) String ver) {
        Map<String, SysCompanyVo> companyMaps = companyService.getMap();
        String md5 = JSONObject.toJSONString(companyMaps);
        if (md5.equals(ver)) {
            return Result.succeed("NO UPDATE");
        }
        MapVo<Map<String, SysCompanyVo>> vo = new MapVo();
        vo.setData(companyMaps);
        vo.setVer(Md5Utils.hash(md5));
        return Result.succeed(vo);
    }


    /**
     * 公司新增或者更新
     *
     * @param sysCompany
     * @return
     */
    @PreAuthorize("hasAnyAuthority('company:post/companys','company:put/companys')")
    @ApiOperation(value = "保存公司")
    @PostMapping("/companys/saveOrUpdate")
    @LogAnnotation(module = "机构", name = "更新")
    public Result saveOrUpdate(@RequestBody SysCompany sysCompany, String keyValue) {
        try {
            companyService.saveOrUpdate(sysCompany, keyValue);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

//    /**
//     * 配置三权
//     *
//     * @param sysCompany
//     * @return
//     */
//    @PreAuthorize("hasAnyAuthority('company:post/companys','company:put/companys')")
//    @ApiOperation(value = "配置三权")
//    @PostMapping("/companys/setAdmins")
//    @LogAnnotation(module = "机构", name = "配置三权")
//    public Result setAdmins(@RequestBody SysCompany sysCompany, String keyValue)  {
//        try {
//            companyService.setAdmins(sysCompany, keyValue);
//            return Result.succeed("操作成功");
//        } catch (Exception e) {
//            return Result.failed(e.getMessage());
//        }
//    }

    /**
     * 删除公司
     * delete /companys/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('company:delete/companys/{id}')")
    @ApiOperation(value = "删除公司")
    @DeleteMapping("/companys/{id}")
    @LogAnnotation(module = "机构", name = "删除")
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            companyService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 导出数据
     *
     * @return
     */
    @GetMapping("/companys/exportExcel")
    @PreAuthorize("hasAuthority('company:post/companys/export')")
    public void export(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        List<SysCompanyExcel> result = companyService.findExcels(params);

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=companys.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
                SysCompanyExcel.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
